package org.example.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import org.junit.Test;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
    //定义一个单例的数据源/连接池对象
    /*private  static final MysqlDataSource DS=new MysqlDataSource();
    static {
        DS.setURL("jdbc:mysql://127.0.0.1:3306/chatroom");
        DS.setUser("root");
        DS.setPassword("123456");
        DS.setUseSSL(false);
        DS.setUseUnicode(true);
        DS.setCharacterEncoding("utf-8");
    }*/
    //优化：改成双重校验锁的单例模式
    private  static MysqlDataSource DS= null;
    private static MysqlDataSource getDS(){
        if (DS==null){
            synchronized (DBUtil.class){
                if (DS==null){
                    DS=new MysqlDataSource();
                    DS.setURL("jdbc:mysql://127.0.0.1:3306/chatroom");
                    DS.setUser("root");
                    DS.setPassword("123456");
                    DS.setUseSSL(false);
                    DS.setUseUnicode(true);
                    DS.setCharacterEncoding("utf-8");
                }
            }
        }
        return DS;
    }

    public static Connection getConnection(){
        try {
            return getDS().getConnection();
        } catch (SQLException e) {
            throw  new RuntimeException("获取数据库连接异常",e);
        }
    }
    //数据库释放资源
    public static void close(Connection c, Statement s){
        close(c,s,null);
    }

        public static void close(Connection c, Statement s, ResultSet r){

            try {
                if (r!=null) r.close();
                if (s!=null) s.close();
                if (c!=null) c.close();
            } catch (SQLException e) {
                throw new RuntimeException("JDBC释放数据资源出错",e);
            }
    }
    @Test
    public void getConnectionTest() {
        System.out.println(getConnection());
    }
}
